<template>
	<view>
		<map class="map" :latitude="latitude" :longitude="longitude" :markers="covers" :scale="18"
			@markertap="showMarkerInfo">
		</map>
		<Common ref="commonRef" @getInfoFromServer="getInfoFromServer"></Common>
	</view>
</template>

<script>
	import Common from "../../components/Common.vue"
	export default {
		props: ["deviceId"],
		components: {
			Common
		},
		created() {
			console.log(this.deviceId)

			//this.deviceId是设备号，带着this.deviceId向服务器发请求
			//TODO 获取初始位置信息,状态，温湿度，警告等

			uni.request({
				url: `${this.$store.state.ipAddr}/getAll`, //仅为示例，并非真实接口地址。
				data: {
					deviceId: parseInt(this.deviceId) //设备号
				},
			
				success: (res) => {
					let data = res.data.data;


					console.log(res)
					//更新锁定状态data.state
					if (data.state == 0) { //已解锁
						this.$refs.commonRef.$data.locking = false;
					} else { //已锁定
						this.$refs.commonRef.$data.locking = true;
					}

					//更新运输状态data.states
					console.log("运输状态data.states", data.status)
					this.$refs.commonRef.$data.state = data.status

					console.log("运输状态改变后data.states", this.$refs.commonRef.$data.state)


					//更新当前坐标
					const currentP = {}
					currentP.lng = data.lng
					currentP.lat = data.lat
					this.$store.commit('updateMyPosition', currentP);
					this.latitude = currentP.lat
					this.longitude = currentP.lng

					// //更新小车坐标
					this.covers[0].latitude = this.latitude
					this.covers[0].longitude = this.longitude
					//解决小车无法重新渲染
					let car = this.covers.shift();
					this.covers.unshift(car);

					this.setAddress()
					this.initCarCallout();

				},
				fail: (res) => {
					console.log("fail:", res)
				}
			});
			
			//设置小车初始坐标
			// this.covers[0].latitude = this.$store.state.myPosition.lat
			// this.covers[0].longitude = this.$store.state.myPosition.lng
			// 	this.setAddress()
			// 	this.initCarCallout();


		},

		mounted() {
			// this.getInfoFromServer();
		},
		computed: {
			// 定位中/定位成功（空闲）/运输中/运输完成（0/1/2/3）
			stateMsg() {
				let curState;
				if (this.states == 0) {
					curState = "定位中"
				} else if (this.states == 1) {
					curState = "空闲"
				} else if (this.states == 2) {
					curState = "运输中"
				} else if (this.states == 3) {
					curState = "运输完成"
				}
				return curState;
			}
		},
		data() {
			return {
				// id: 0, // 使用 marker点击事件 需要填写id
				title: 'map',
				myPosition: this.$store.state.myPosition,
				latitude: this.$store.state.myPosition.lat,
				longitude: this.$store.state.myPosition.lng,
				address: "",
				//定位中/定位成功（空闲）/运输中/运输完成（0/1/2/3）
				states: 2,
				temperature: 0,
				humidity: 0,
				covers: [{
					id: 0,
					title: "小车",
					latitude: 39.909,
					longitude: 116.39742,
					iconPath: '../../static/car.png',
					label: {
						content: `设备号：${this.deviceId}`,
					},
					callout: {
						content: "我是小车",
						color: "#000000",
						fontSize: 14,
						borderRadius: 10,
						bgColor: "#ffffff",
						padding: 10,
						display: "BYCLICK", // 气泡的显示状态，"BYCLICK" 表示点击标记时显示
					}
				}, ],

			}
		},
		methods: {
			//根据经纬度设置地址
			setAddress() {
				let longitude = this.longitude
				let latitude = this.latitude


				uni.request({
					url: 'https://restapi.amap.com/v3/geocode/regeo', //仅为示例，并非真实接口地址。
					data: {
						output: 'json',
						location: `${longitude},${latitude}`,
						key: '890b847af96b82c55ff726a0a9154836',
						extensions: 'base',
						batch: false
					},
					success: (res) => {
						const formattedAddress = res.data.regeocode.formatted_address;
						// 更新 store 中的地址
						this.$store.commit('updateMyAddress', formattedAddress);
					}
				});
			},

			//改变点的坐标
			changePointPosition(lat, lng) {
				//1.画出当前点（经过的点）
				let p = {};
				p.longitude = this.$store.state.myPosition.lng.toFixed(6)
				p.latitude = this.$store.state.myPosition.lat.toFixed(6)
				if (this.covers.length == 1) {
					p.iconPath = '../../static/start.png'
				} else {
					p.iconPath = '../../static/pass.png'
				}
				p.id = this.covers.length
				let callout = {
					color: "#000000",
					fontSize: 14,
					borderRadius: 10,
					bgColor: "#ffffff",
					padding: 10,
					display: "BYCLICK", // 气泡的显示状态，"BYCLICK" 表示点击标记时显示
				}
				callout.content = "温度：" + this.temperature + " ℃" +
					"\n湿度：" + this.humidity + " %RH" +
					"\n经度：" + this.longitude.toFixed(6) +
					"\n纬度：" + this.latitude.toFixed(6) +
					"\n地址：" + this.handleLongString(this.$store.state.myAddress)
				p.callout = callout
				this.covers.push(p);

				//2.更新小车的位置
				//2.1 取出小车元素
				const car = this.covers.shift();
				//2.2更新位置
				// car.longitude += 0.0001;
				// car.latitude += 0.0001;
				car.longitude = lng;
				car.latitude = lat;
				this.longitude = car.longitude
				this.latitude = car.latitude

				//2.3提交小车新的坐标
				const currentP = {}
				currentP.lng = car.longitude
				currentP.lat = car.latitude
				this.$store.commit('updateMyPosition', currentP);
				//2.4重新设置小车的地址
				this.setAddress();
				//2.5设置小车的callout气泡
				car.callout.content = "我是小车\n状态：" + this.stateMsg +
					"\n温度：" + this.temperature + " ℃" +
					"\n湿度：" + this.humidity + " %RH" +
					"\n经度：" + car.longitude.toFixed(6) + "\n纬度：" + car.latitude.toFixed(6) +
					"\n地址：" + this.handleLongString(this.$store.state.myAddress)
				//2.6.将小车元素放回
				this.covers.unshift(car);
			},
			// 新增的方法，用于每秒钟改变坐标
			startUpdatingCoordinates() {
				// 使用 setInterval 每秒钟执行一次 changePointPosition 方法
				this.updateInterval = setInterval(() => {
					this.changePointPosition();
				}, 2000); // 1000 毫秒等于 1 秒
			},
			//显示信息
			showMarkerInfo(e) {
				console.log("id", e.detail.markerId)
				// if (e.detail.markerId == 0) {
				// 	if (this.updateInterval != null) {
				// 		clearInterval(this.updateInterval);
				// 	} else {
				// 		this.startUpdatingCoordinates()
				// 	}
				// }
			},
			//设置小车的初始气泡
			initCarCallout() {
				this.covers[0].callout.content += "\n状态：" + this.stateMsg;
				this.covers[0].callout.content += "\n温度：" + this.temperature + " ℃";
				this.covers[0].callout.content += "\n湿度：" + this.humidity + "% RH";
				this.covers[0].callout.content += "\n经度：" + this.longitude + "\n纬度：" + this.latitude;
				this.covers[0].callout.content += "\n地址：" + this.handleLongString(this.$store.state.myAddress)
			},
			handleLongString(inputString) {

				let resultString = '';
				for (let i = 0; i < inputString.length; i++) {
					resultString += inputString[i];
					if (i === 9) {
						resultString += '\n';
					} else if ((i - 9) % 13 === 0 && i > 9) {
						resultString += '\n';
					}
				}

				return resultString;
			},
			getInfoFromServer() {

				console.log("getInfoFromServer")
				uni.connectSocket({
					url: 'ws://mark.w1.luyouxia.net/socket',
					header: {
						'content-type': 'application/json'
					},
					protocols: ['protocol1'],
					method: 'GET'
				});
				var that = this;
				uni.onSocketMessage(function(res) {
					console.log('收到服务器内容：' + res.data);

					let data = JSON.parse(res.data);
					if (data.code) { //有code
						// console.log('警告信息：', data);
						//更新警告
						that.$refs.commonRef.$data.warn = data.code
					} else { //无code
						console.log('坐标信息：', data);
						//1.更新温湿度
						// 通过 ref 获取子组件实例
						that.$refs.commonRef.$data.temperature = data.temp
						that.$refs.commonRef.$data.humidity = data.humi
						this.temperature = data.temp
						this.humidity = data.humi
						//2.更新坐标
						that.changePointPosition(data.lat, data.lng)
					}

				});
			}

		}

	}
</script>
<style>
	.content {
		flex: 1;
	}

	.map {
		flex: 1;
		width: 100%;
		height: 500px;
	}
</style>